<?php

namespace App\Http\Requests\Api;

use App\Models\Order;
use App\Models\Schedule;
use Dingo\Api\Http\FormRequest;

class OrdersRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        if ($this->isMethod('GET')) {
            return [
                'status' => [
                    'in:' . implode(',', array_map(function ($item) {
                        if (strstr($item, "cancel")) {
                            return strstr($item, "cancel");
                        } else {
                            return $item;
                        }
                    }, array_keys(Order::$STATUS_MAP))) . ',processing',
                ],
                'refund_status' => [
                    'in:' . implode(',', array_keys(Order::$REFUND_STATUS_MAP)),
                ],
            ];
        }

        if ($this->isMethod('POST')) {
            return [
                'contact_name' => [
                    'required',
                    'max:20',
                ],
                'contact_phone' => [
                    'required',
                    'regex:/^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/',
                ],
                'goods_id' => [
                    'required',
                    'integer',
                    'exists:products,id',
                ],
                'schedule_id' => [
                    'required',
                    'exists:schedules,id',
                    function ($attribute, $value, $fail) {
                        //判断是否被占用
                        $status = Schedule::where('id', $value)->value('status');

                        if ($status != 0) {
                            $fail($attribute . ' ' . trans('api.schedule_is_occupied'));

                            return;
                        }
                    },
                ],
            ];
        }

        if ($this->isMethod('PUT')) {
            return [
                'id' => [
                    'required',
                    'integer',
                    'exists:orders,id',
                ],
            ];
        }
    }

}
